<!--
 * @Author: ac98l
 * @Date: 2023-02-10 09:13:21
 * @LastEditors: ac98l
 * @LastEditTime: 2023-03-09 16:47:05
 * @Description: 暂无说明
-->

<template>
  <div class="car-coninater">
    <!-- <div class="w">
      <Alert show-icon closable type="warning" class="tips-box">
        小提示
        <Icon type="ios-lightbulb-outline" slot="icon"></Icon>
        <template slot="desc">请点击商品前的选择框，选择购物车中的商品，点击付款即可。</template>
      </Alert>
    </div> -->
    <div class="search-nav">
      <div class="search-nav-container w">
        <ul>
          <li>我的购物车</li>
        </ul>
      </div>
    </div>
    <div class="w heiheib">
      <el-table ref="myTable" :data="myCarData" border style="width: 100%" class="order-table" @selection-change="handleSelectionChange" v-loading="tableLoading">
        <template slot="empty">
          <p class="emptyText">您的购物车没有商品，请先
            <router-link class="link-type" :to="'/'"><span style="cursor: pointer;">添加商品</span> </router-link>到购物车再点击购买
          </p>
        </template>
        <el-table-column type="selection" width="44" align="center">
        </el-table-column>
        <el-table-column label="商品快照" width="130px" align="center">
          <template slot-scope="scope">
            <viewer>
              <img :src="scope.row.picture" style="width:80px;height: 70px;cursor:pointer ">
            </viewer>
          </template>
        </el-table-column>
        <el-table-column prop="commodity" label="标题" min-width="260" show-show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="price" label="餐品单价" width="120" align="center">
        </el-table-column>
        <el-table-column prop="addNumber" label="数量" width="240" align="center">
          <template slot-scope="scope">
            <el-input-number @change="addNumberChange(scope.row)" v-model="scope.row.addNumber" :min="1" :max="10"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="餐盒" width="280" align="center" show-show-overflow-tooltip :render-header="renderHeader">
          <template slot-scope="scope">
            <div v-for="(items,index) in boxArray" :key="index">
              <el-radio-group v-model="scope.row.box" @change="itemRadioChange(scope.row,items.price)">
                <el-radio :label="items.id">{{ items.boxName }}</el-radio>
              </el-radio-group>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <i class="el-icon-circle-close" @click="deleteGoods(scope.row)"></i>
            <!-- <el-button type="danger" size="mini" icon="el-icon-magic-delete" @click="deleteGoods(scope.row)">从购物车移出</el-button></el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!--  <div class="remarks-container">
        <h3>备注</h3>
        <el-input class="remarks-input" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="在这里填写备注信息" v-model="textaremarksrea2">
        </el-input>
      </div> -->
      <div class="pay-container">
        <div class="pay-box">
          <p><span>商品总额：</span> <span class="money">
              <Icon type="social-yen"></Icon> {{totalPrice.toFixed(2)}}
            </span></p>
          <div class="pay-btn">
            <Button style="margin-right:12px;" type="error" size="large" @click="resetShopCar()">清空购物车</Button></Button>
            <Button type="error" :disabled="goodsCheckList.length == 0" size="large" @click="order()">提交订单</Button>
          </div>
        </div>
      </div>
    </div>
    <el-drawer title="餐盒一览" :visible.sync="drawerVisible" direction="rtl">
      <div style="padding:12px;" class="drawer-coninater">
        <el-descriptions style="margin: 14px 0;" :title="item.boxName" :column="2" v-for="(item,index) in boxArray" :key="index" border direction="vertical">
          <el-descriptions-item label="餐盒图片" :contentStyle='contentStyle' :labelStyle='labelStyle'>
            <viewer>
              <img :src="item.picture" alt="餐盒图片" style="width:80px;height: 70px;cursor:pointer ">
            </viewer>
          </el-descriptions-item>
          <el-descriptions-item label="餐盒信息">
            <span>{{ item.boxSize}}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { goOrder, getShoppingCartList, orderSave, removeShoppingCart, clearShoppingCart, getBoxList } from '@/api/goods'
export default {
  data() {
    return {
      contentStyle: {
        'text-align': 'center',
      },
      //label样式
      labelStyle: { 'width': '100px' },
      myCarData: [],
      checkAddress: {
        name: '未选择',
        address: '请选择地址'
      },
      remarks: '',
      goodsCheckList: [],
      boxArray: [],
      tableLoading: false,
      drawerVisible: false,
      defaultPrice: 0,
      totalPrice: 0 // 总价
    }
  },
  async created() {
    // this.$store.dispatch("loadAddress")
    if (!sessionStorage.getItem('userToken')) {
      this.$alert('请登录', '系统提示', {
        confirmButtonText: '确定',
        callback: action => {
          this.$router.push({ path: '/dianShangLogin' }).catch(() => { });
        }
      }).catch(() => { });
    } else {
      this.tableLoading = true
      // 获取餐盒列表
      const result = await getBoxList()
      this.boxArray = result.data
      this.getCarList()
    }
  },
  // computed: {
  //   totalPrice() {
  //     let price = 0;
  //     this.goodsCheckList.forEach(item => {
  //       price += (item.price * item.addNumber) + (item.boxPrice * item.addNumber);
  //     });
  //     return price;
  //   }
  // },
  watch: {
    'goodsCheckList': {
      handler: function () {
        this.totalPrice = 0
        this.goodsCheckList.forEach(item => {
          this.totalPrice += (item.price * item.addNumber) + (item.boxPrice * item.addNumber);
        });
      },
      deep: true
    }
  },

  methods: {
    itemRadioChange(a, b) {
      a.boxPrice = Number(b)
    },
    renderHeader(h) {
      let that = this
      return h("div", null, [
        h("span", {
          class: "zhangzhen",
          on: {
            click: function () {
              that.aaaaa()
            }
          }
        }, [
          h("span", "餐盒"),
          h("i", {
            class: "el-icon-question"
          })
        ]),
      ]);
    },
    aaaaa() {
      this.drawerVisible = true
    },
    getCarList() {
      getShoppingCartList().then(res => {
        this.boxArray.forEach(item => {
          if (item.id == 1) {
            this.defaultPrice = Number(item.price)
          }
        })
        res.data.forEach(item => {
          item.box = 1
          item.boxPrice = this.defaultPrice
        })
        this.myCarData = res.data
        this.tableLoading = false
      })
    },
    handleSelectionChange(e) {
      this.goodsCheckList = e;
    },
    addNumberChange(row) {
      // 同步多选数据
      if (this.goodsCheckList.length > 0) {
        this.goodsCheckList.forEach(item => {
          if (item.id == row.id) {
            item.addNumber = row.addNumber
          }
        })
      }
    },
    changeAddress(data) {
      const father = this;
      this.$store.state.goodsDetail.userAddress.forEach(item => {
        if (item.addressId === data) {
          father.checkAddress.name = item.name;
          father.checkAddress.address = `${item.name} ${item.province} ${item.city} ${item.address} ${item.phone} ${item.postalcode}`;
        }
      })
    },
    // 删除某个商品
    deleteGoods(row) {
      this.$modal.confirm('是否将' + row.commodity + '移出购物车').then(() => {
        removeShoppingCart({ id: row.id }).then(res => {
          this.$modal.msgSuccess('已成功从购物车移出')
          this.getCarList()
        })
      }).catch(e => { })
    },
    // 清空购物车
    resetShopCar() {
      this.$modal.confirm('是否清空购物车').then(() => {
        clearShoppingCart().then(res => {
          this.$modal.msgSuccess('清空购物车成功')
          this.getCarList()
        })
      }).catch(e => { })
    },
    order() {
      if (this.goodsCheckList.length > 0) {
        let saveOrderList = JSON.parse(JSON.stringify(this.goodsCheckList))
        // 生成订单 替换需要的字段名称
        saveOrderList = JSON.parse(JSON.stringify(saveOrderList).replace(/id/g, "shopId").replace(/userId/g, "businessId"));
        // totalAmount
        saveOrderList.forEach(item => {
          item.status = 1
          item.totalAmount = item.addNumber * item.price
        })
        // 调用生成订单接口
        orderSave(saveOrderList).then(res => {
          this.$modal.msgSuccess('提交成功')
          this.getCarList()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header {
  margin-bottom: 0px !important;
  padding-bottom: 16px;
  font-size: 18px;
  font-weight: 500;
  border-bottom: 2px solid rgb(233, 97, 64);
}
.drawer-coninater {
  max-height: calc(100vh - 100px);
  overflow: scroll;
}
.car-coninater {
  height: calc(100% - 162px);
}
.tips-box {
  margin-top: 12px;
}
.heiheib {
  height: 100%;
  max-height: calc(100% - 88px);
  // min-height: calc(100% - 552px);
}
// 表格
.order-table {
  margin-bottom: 12px;
  ::v-deep .zhangzhen {
    cursor: pointer;
    &:hover {
      color: rgb(233, 97, 64);
    }
  }
}
// 收货人信息i
.address-container {
  margin-top: 15px;
}
.address-box {
  margin-top: 15px;
  padding: 15px;
  border: 1px #ccc dotted;
}
.address-check {
  margin: 15px 0px;
  height: 36px;
  display: flex;
  align-items: center;
}
.address-check-name {
  width: 120px;
  display: flex;
  justify-content: center;
  align-content: center;
  background-color: #ccc;
}
.address-check-name span {
  width: 120px;
  height: 36px;
  font-size: 14px;
  line-height: 36px;
  text-align: center;
  color: #fff;
  background-color: #d7593e;
}
.address-detail {
  padding-left: 15px;
  font-size: 14px;
  color: #999999;
}

.remarks-container {
  margin: 15px 0px;
}
.remarks-input {
  margin-top: 15px;
}
// 支付
.pay-container {
  margin: 15px;
  display: flex;
  justify-content: flex-end;
}
.pay-box {
  font-size: 18px;
  font-weight: bolder;
  color: #495060;
}
.money {
  font-size: 26px;
  color: #f90013;
}
.pay-btn {
  margin: 15px 0px;
  display: flex;
  justify-content: flex-end;
}
</style>